﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Net;
using System.IO;
using Newtonsoft.Json;
using System.Threading;

namespace __moov
{
    public partial class FrmLogin : Form
    {
        // This block is used to animate the window
        public const int AW_ACTIVATE = 0x20000;
        public const int AW_HIDE = 0x10000;
        public const int AW_BLEND = 0x80000;
        public const int AW_CENTER = 0x00000010;
        public const int AW_SLIDE = 0X40000;
        public const int AW_HOR_POSITIVE = 0x1;
        public const int AW_HOR_NEGATIVE = 0X2;
        public const int AW_VER_POSITIVE = 0x00000004;
        public const int AW_VER_NEGATIVE = 0x00000008;

        Thread worker;
        public bool animateForm = true;
        public string userID;
        public bool isUserExists = false;
        public const string defaultMobileText = "MOBILE";
        public const string defaultEmailText = "EMAIL";
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int AnimateWindow(IntPtr hwand, int dwTime, int dwFlags);
        // -------------------------------------------------------//
       
        public FrmLogin()
        {
            InitializeComponent();

            this.SetDesktopLocation(Screen.PrimaryScreen.WorkingArea.Right - this.Width,
              Screen.PrimaryScreen.WorkingArea.Bottom - this.Height);

            //enable link only when user exists
            this.btnLinkAcc.Enabled = false;
        }

        private void envFrmLoad(object sender, EventArgs e)
        {
            //Performs window animation
            if (animateForm) AnimateWindow(this.Handle, 500, AW_ACTIVATE | AW_SLIDE | AW_VER_NEGATIVE);

        }


        private void envBtnSettingClick(object sender, EventArgs e)
        {
            //display the settings form
            FrmSettings frmSettings = new FrmSettings();
            frmSettings.ShowDialog();

        }

        private void envBtnCloseClick(object sender, EventArgs e)
        {
            AnimateWindow(this.Handle, 500, AW_ACTIVATE | AW_SLIDE | AW_VER_POSITIVE | AW_HIDE);
            this.Close();
        }

        private void lblRegisterLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            //display the registeration form
            FrmRegister frmRegister = new FrmRegister();
            frmRegister.ShowDialog(this);
        }

        private void envTxtPhoneGainFocus(object sender, EventArgs e)
        {
            if (txtPhone.Text == defaultMobileText)
            txtPhone.Clear();
        }

        private void envTxtPhoneLooseFocus(object sender, EventArgs e)
        {
            if (txtPhone.Text.Length < 1)
            txtPhone.Text = defaultMobileText;

        }

        private void envTxtEmailGainFocus(object sender, EventArgs e)
        {
            if (txtEmail.Text == defaultEmailText)
            txtEmail.Clear();
        }

        private void envTxtEmailLooseFocus(object sender, EventArgs e)
        {
            if (txtEmail.Text.Length < 1)
            txtEmail.Text = defaultEmailText;

        }

        private void envTxtPhoneTextChanged(object sender, EventArgs e)
        {
            if (txtPhone.Text.Length < 6) return;
            //miss a turn
            if (timer.Enabled == false)
            {
                timer.Start();
                worker = new Thread(validate_msisdn);
                worker.Start();
            }   else timer.Stop();
        }

        
        public void validate_msisdn()
        {
            String[] url = null;
            String[] urlParam = null;
            isUserExists = false;
            userID = null;
            
            this.Invoke((MethodInvoker)delegate
            {
                //Enable email field if disabled
                this.txtEmail.Enabled = true;
                //Enable activation only when user exists
                this.btnLinkAcc.Enabled = false;

                if (txtPhone.Text == null || txtPhone.Text == "MOBILE" || txtPhone.Text.Length == 0) { this.pbMobile.Image = null; return; }
                if (!System.Text.RegularExpressions.Regex.IsMatch(txtPhone.Text, @"^[0-9]{4,15}$", System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                {
                    this.pbMobile.Image = Properties.Resources.deny;
                }

                //load while requesting from api service
                this.pbMobile.Image = Properties.Resources.loading;

                url = new String[3];
                url[0] = Properties.Settings.Default.requestPartialURL;
                url[1] = "0";
                url[2] = "users";

                urlParam = new String[4];
                urlParam[0] = "fields=id";
                urlParam[1] = "msisdn="+txtPhone.Text;
                urlParam[2] = "status=A";
                urlParam[3] = "fmt=json";
            });

            try
            {
                if (url == null) { this.pbMobile.Image = null; return; };
                //make request
                String uri = String.Join("/", url) + "?" + String.Join("&", urlParam);
                WebRequest webRequest = WebRequest.Create(uri);
                webRequest.Method = "GET";
                WebResponse webResponse = webRequest.GetResponse();

                //Prepare to read response
                StreamReader responseReader = new StreamReader(webResponse.GetResponseStream());
                string str = null;
                while ((str = responseReader.ReadLine()) != null)
                {
                    UsersPOCO[] apiUsersResponse = JsonConvert.DeserializeObject<UsersPOCO[]>(str);
                    foreach (UsersPOCO requestedUser in apiUsersResponse)
                    {
                        if (requestedUser.id != null)
                        {
                            isUserExists = true;
                            userID = requestedUser.id;
                            Properties.Settings.Default.userId = userID;
                        }
                    }
                }

                this.Invoke((MethodInvoker)delegate
                {
                    if (isUserExists)
                    {   
                        //set email field to read only
                        this.txtEmail.Enabled = false;
                        //Enable activation only when user exists
                        this.btnLinkAcc.Enabled = true;
                        this.btnLinkAcc.Refresh();
                        this.pbMobile.Image = Properties.Resources.accept;
                    }
                    else this.pbMobile.Image = Properties.Resources.deny;
                });


            }
            catch (Exception ex)
            {
                //write to event log
                System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog();
                appLog.Source = "Moov - Client";
                appLog.WriteEntry(ex.ToString());

                //clear the picture box
                this.Invoke((MethodInvoker)delegate
                {
                    this.pbMobile.Image = null;
                });
            }
            

            return;
        }

        public void validate_email()
        {
            String[] url = null;
            String[] urlParam = null;
            isUserExists = false;
            userID = null;            

            this.Invoke((MethodInvoker)delegate
            {
                //Enable email field if disabled
                this.txtPhone.Enabled = true;
                //Enable activation only when user exists
                this.btnLinkAcc.Enabled = false;

                if (txtEmail.Text == null || txtEmail.Text == "EMAIL" || txtEmail.Text.Length == 0) { this.pbEmail.Image = null; return; }
                if (!System.Text.RegularExpressions.Regex.IsMatch(txtEmail.Text, @"^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,4})$", System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                {
                    this.pbMobile.Image = Properties.Resources.deny;
                }

                //load while requesting from api service
                this.pbMobile.Image = Properties.Resources.loading;

                url = new String[3];
                url[0] = Properties.Settings.Default.requestPartialURL;
                url[1] = "0";
                url[2] = "users";

                urlParam = new String[4];
                urlParam[0] = "fields=id";
                urlParam[1] = "msisdn=" + txtEmail.Text;
                urlParam[2] = "status=A";
                urlParam[3] = "fmt=json";
            });

            try
            {
                if (url == null) { this.pbEmail.Image = null; return; };
                //make request
                String uri = String.Join("/", url) + "?" + String.Join("&", urlParam);
                WebRequest webRequest = WebRequest.Create(uri);
                webRequest.Method = "GET";
                WebResponse webResponse = webRequest.GetResponse();

                //Prepare to read response
                StreamReader responseReader = new StreamReader(webResponse.GetResponseStream());
                string str = null;
                while ((str = responseReader.ReadLine()) != null)
                {
                    ContactsPOCO[] apiUsersResponse = JsonConvert.DeserializeObject<ContactsPOCO[]>(str);
                    foreach (ContactsPOCO requestedUser in apiUsersResponse)
                    {
                        if (requestedUser.id != null)
                        {
                            isUserExists = true;
                            userID = requestedUser.id;
                        }
                    }
                }

                this.Invoke((MethodInvoker)delegate
                {
                    if (isUserExists)
                    {
                        this.pbEmail.Image = Properties.Resources.accept;
                        //set email field to read only
                        this.txtPhone.Enabled = false;
                        this.btnLinkAcc.Enabled = true;
                    }
                    else this.pbEmail.Image = Properties.Resources.deny;
                });


            }
            catch (Exception ex)
            {
                //write to event log
                System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog();
                appLog.Source = "Moov - Client";
                appLog.WriteEntry(ex.ToString());

                //clear the picture box
                this.Invoke((MethodInvoker)delegate
                {
                    this.pbEmail.Image = null;
                });
            }


            return;
        }

        private void envTxtEmailTextChanged(object sender, EventArgs e)
        {
            worker = new Thread(validate_email);
            worker.Start();
        }

        private void btnLinkAccClick(object sender, EventArgs e)
        {
            FrmVerify frmVerify = new FrmVerify(txtPhone.Text, txtEmail.Text);
            frmVerify.ShowDialog(this);
        }

        

       
   
    }
}
